package org.sean.contactdemo.service;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sean.contactdemo.db.DBInstance;
import org.sean.contactdemo.db.GroupDAO;
import org.sean.contactdemo.db.UserDAO;
import org.sean.contactdemo.domain.Group;
import org.sean.contactdemo.domain.User;
import org.sean.contactdemo.util.ClientSession;
import org.sean.contactdemo.util.StringHelper;

public class UserServiceImpl implements UserService {
	
	private static Log log = LogFactory.getLog("");

	@Override
	public User addNewUser(User newUser) {
		return addNewUser(newUser, null);
	}

	@Override
	public User addNewUser(User newUser, String groupName) {
		UserDAO userDao = new UserDAO();
		User user = userDao.addUser(newUser);
		//After user added, one default Group is needed.
		Group group = new Group(user.getUserId());
		if (StringHelper.isNotEmpty(groupName)){
			group.setGroupName(groupName);
		}
		group.setDefault(true);
		GroupDAO groupDao = new GroupDAO(userDao.getConnection());
		groupDao.addGroup(group);
		DBInstance.closeConnection(userDao.getConnection());
		return user;
	}

	@Override
	public User loginWithUser(String userAccount, String userPassword) {
		UserDAO userDao = new UserDAO();
		User user = userDao.loginWithUser(userAccount, userPassword);
		//Set user information to session
		if (user != null){
			ClientSession session = ClientSession.getInstance();
			session.setCurrentUserId(user.getUserId());
			session.setUser(user);
			session.setValid(true);
			session.setLoginTime(new Date());
			user.setLastLogin(session.getLoginTime());
			userDao.updateUser(user);
			log.info("LOGIN SUCCESSFULLY <" + user.getUserAccount() + ">, START TIME AT <" + session.getLoginTime().toLocaleString() + "> !");
		} else {
			log.info("LOGIN FAILURE WITH USER <" + userAccount + ">!");
		}
		DBInstance.closeConnection(userDao.getConnection());
		return user;
	}
}
